package cn.jtfadmin.activiti.service.impl;

import cn.jtfadmin.activiti.domain.entity.FormDesignEntity;
import cn.jtfadmin.activiti.repository.FormDesignRepository;
import cn.jtfadmin.activiti.service.UeditorActService;
import cn.jtfadmin.activiti.ueditor.define.BaseState;
import cn.jtfadmin.activiti.ueditor.define.State;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * 富文本和act
 */
@Service
public class UeditorActServiceImpl implements UeditorActService {

    @Autowired
    private FormDesignRepository formDesignRepository;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public State get(HttpServletRequest request) {
        String type = request.getParameter("type");
        if("updateFormDesign".equals(type)){
            FormDesignEntity entity = formDesignRepository.findById(request.getParameter("formDesignId")).get();
            String content = entity.getContent();
            State state = new BaseState();
            state.putInfo("result", Objects.isNull(content)?"":content);
            return state;
        }
        return null;
    }

    @Override
    @Transactional
    public State save(HttpServletRequest request) {
        String type = request.getParameter("type");
        if("updateFormDesign".equals(type)){
            FormDesignEntity entity = formDesignRepository.findById(request.getParameter("formDesignId")).get();
            String content = null;
            try {
                content = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
            } catch (IOException e) {
                throw new IllegalArgumentException(e);
            }

            entity.setContent(content);

            formDesignRepository.save(entity);
            State state = new BaseState();
            return state;
        }
        return null;
    }
}
